package com.msxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.msxt.annotation.IgnoreAuth;
import com.msxt.constant.JwtClaimsConstant;
import com.msxt.dto.ShangjiaEntity;
import com.msxt.dto.YonghuEntity;
import com.msxt.properties.JwtProperties;
import com.msxt.result.R;
import com.msxt.service.ShangjiaService;
import com.msxt.service.TokenService;
import com.msxt.utils.JwtUtil;
import com.msxt.utils.MPUtil;
import com.msxt.utils.PageUtils;
import com.msxt.view.ShangjiaView;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商家
 * 后端接口
 */
@Slf4j
@RestController
@RequestMapping("/shangjia")
public class ShangjiaController {
	@Autowired
	private ShangjiaService shangjiaService;

	@Autowired
	private JwtProperties jwtProperties;

	// 新增：OSS基础URL配置
	@Value("${oss.base-url:}")
	private String ossBaseUrl;

	/**
	 * 登录
	 */
	@IgnoreAuth
	@PostMapping("/login")
	public R login(String username, String password, HttpServletRequest request) {
		ShangjiaEntity u = shangjiaService.getOne(new QueryWrapper<ShangjiaEntity>().eq("shangjiazhanghao", username));
		if(u == null || !u.getMima().equals(password)) {
			return R.error("账号或密码不正确");
		}

		Map<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.SHANGJIA_ID, u.getId());
		claims.put(JwtClaimsConstant.USERNAME, username);
		claims.put(JwtClaimsConstant.ROLE, "商家");
		claims.put(JwtClaimsConstant.TABLE_NAME, "shangjia");

		String token = JwtUtil.createJWT(jwtProperties.getShangjiaSecretKey(),
				jwtProperties.getShangjiaTtl(),
				claims);
		return R.ok().put("token", token);
	}

	/**
	 * 注册
	 */
	@IgnoreAuth
	@PostMapping("/register")
	public R register(@RequestBody ShangjiaEntity shangjia) {
		// ValidatorUtils.validateEntity(shangjia);
		ShangjiaEntity u = shangjiaService.getOne(new QueryWrapper<ShangjiaEntity>().eq("shangjiazhanghao", shangjia.getShangjiazhanghao()));
		if(u != null) {
			return R.error("注册用户已存在");
		}
		Long uId = new Date().getTime();
		shangjia.setId(uId);

		// 新增：处理头像URL
		if (StringUtils.isNotBlank(shangjia.getTouxiang())) {
			shangjia.setTouxiang(ensureFullUrl(shangjia.getTouxiang()));
		}

		shangjiaService.save(shangjia);
		return R.ok();
	}

	/**
	 * 退出
	 */
	@GetMapping("/logout")
	public R logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return R.ok("退出成功");
	}

	/**
	 * 获取用户的session用户信息
	 */
	@GetMapping("/session")
	public R getCurrUser(HttpServletRequest request) {
		// 从请求属性中获取用户ID
		Object userIdObj = request.getAttribute("userId");
		if (userIdObj == null) {
			log.warn("未找到商家ID属性");
			return R.error(401, "商家未登录");
		}

		Long id;
		try {
			id = Long.parseLong(userIdObj.toString());
		} catch (NumberFormatException e) {
			log.error("商家ID格式错误: {}", userIdObj);
			return R.error(401, "无效的商家ID");
		}

		log.info("获取商家ID: {}", id);

		ShangjiaEntity u = shangjiaService.getById(id);
		if (u == null) {
			return R.error(401, "商家不存在");
		}

		// 新增：确保头像URL是完整的
		u.setTouxiang(ensureFullUrl(u.getTouxiang()));

		return R.ok().put("data", u);
	}

	/**
	 * 密码重置
	 */
	@IgnoreAuth
	@PostMapping("/resetPass")
	public R resetPass(String username, HttpServletRequest request) {
		ShangjiaEntity u = shangjiaService.getOne(new QueryWrapper<ShangjiaEntity>().eq("shangjiazhanghao", username));
		if(u == null) {
			return R.error("账号不存在");
		}
		u.setMima("123456");
		shangjiaService.updateById(u);
		return R.ok("密码已重置为：123456");
	}

	/**
	 * 后端列表
	 */
	@GetMapping("/page")
	public R page(@RequestParam Map<String, Object> params,
				  ShangjiaEntity shangjia,
				  HttpServletRequest request) {
		QueryWrapper<ShangjiaEntity> wrapper = new QueryWrapper<>();
		PageUtils page = shangjiaService.queryPage(params,
				MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, shangjia), params), params));

		// 新增：处理列表中的头像URL
		if (page != null && page.getList() != null) {
			for (Object item : page.getList()) {
				if (item instanceof ShangjiaEntity) {
					ShangjiaEntity entity = (ShangjiaEntity) item;
					entity.setTouxiang(ensureFullUrl(entity.getTouxiang()));
				}
			}
		}

		return R.ok().put("data", page);
	}

	/**
	 * 前端列表
	 */
	@IgnoreAuth
	@GetMapping("/list")
	public R list(@RequestParam Map<String, Object> params,
				  ShangjiaEntity shangjia,
				  HttpServletRequest request) {
		QueryWrapper<ShangjiaEntity> wrapper = new QueryWrapper<>();
		PageUtils page = shangjiaService.queryPage(params,
				MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, shangjia), params), params));

		// 新增：处理列表中的头像URL
		if (page != null && page.getList() != null) {
			for (Object item : page.getList()) {
				if (item instanceof ShangjiaEntity) {
					ShangjiaEntity entity = (ShangjiaEntity) item;
					entity.setTouxiang(ensureFullUrl(entity.getTouxiang()));
				}
			}
		}

		return R.ok().put("data", page);
	}

	/**
	 * 列表
	 */
	@GetMapping("/lists")
	public R list(ShangjiaEntity shangjia) {
		QueryWrapper<ShangjiaEntity> wrapper = new QueryWrapper<>();
		wrapper.allEq(MPUtil.allEQMapPre(shangjia, "shangjia"));

		List<ShangjiaEntity> list = shangjiaService.list(wrapper);

		// 新增：处理列表中的头像URL
		for (ShangjiaEntity entity : list) {
			entity.setTouxiang(ensureFullUrl(entity.getTouxiang()));
		}

		return R.ok().put("data", list);
	}

	/**
	 * 查询
	 */
	@GetMapping("/query")
	public R query(ShangjiaEntity shangjia) {
		QueryWrapper<ShangjiaEntity> wrapper = new QueryWrapper<>();
		wrapper.allEq(MPUtil.allEQMapPre(shangjia, "shangjia"));
		ShangjiaView shangjiaView = shangjiaService.selectView(wrapper);

		// 新增：处理头像URL
		if (shangjiaView != null) {
			shangjiaView.setTouxiang(ensureFullUrl(shangjiaView.getTouxiang()));
		}

		return R.ok("查询商家成功").put("data", shangjiaView);
	}

	/**
	 * 后端详情
	 */
	@GetMapping("/info/{id}")
	public R info(@PathVariable("id") Long id) {
		ShangjiaEntity shangjia = shangjiaService.getById(id);

		// 新增：确保头像URL是完整的
		if (shangjia != null) {
			shangjia.setTouxiang(ensureFullUrl(shangjia.getTouxiang()));
		}

		return R.ok().put("data", shangjia);
	}

	/**
	 * 前端详情
	 */
	@IgnoreAuth
	@GetMapping("/detail/{id}")
	public R detail(@PathVariable("id") Long id) {
		ShangjiaEntity shangjia = shangjiaService.getById(id);

		// 新增：确保头像URL是完整的
		if (shangjia != null) {
			shangjia.setTouxiang(ensureFullUrl(shangjia.getTouxiang()));
		}

		return R.ok().put("data", shangjia);
	}

	/**
	 * 后端保存
	 */
	@PostMapping("/save")
	public R save(@RequestBody ShangjiaEntity shangjia,
				  HttpServletRequest request) {
		shangjia.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
		// ValidatorUtils.validateEntity(shangjia);
		ShangjiaEntity u = shangjiaService.getOne(new QueryWrapper<ShangjiaEntity>().eq("shangjiazhanghao", shangjia.getShangjiazhanghao()));
		if(u != null) {
			return R.error("用户已存在");
		}

		// 新增：处理头像URL
		if (StringUtils.isNotBlank(shangjia.getTouxiang())) {
			shangjia.setTouxiang(ensureFullUrl(shangjia.getTouxiang()));
		}

		shangjia.setId(new Date().getTime());
		shangjiaService.save(shangjia);
		return R.ok();
	}

	/**
	 * 前端保存
	 */
	@PostMapping("/add")
	public R add(@RequestBody ShangjiaEntity shangjia,
				 HttpServletRequest request) {
		shangjia.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
		// ValidatorUtils.validateEntity(shangjia);
		ShangjiaEntity u = shangjiaService.getOne(new QueryWrapper<ShangjiaEntity>().eq("shangjiazhanghao", shangjia.getShangjiazhanghao()));
		if(u != null) {
			return R.error("用户已存在");
		}

		// 新增：处理头像URL
		if (StringUtils.isNotBlank(shangjia.getTouxiang())) {
			shangjia.setTouxiang(ensureFullUrl(shangjia.getTouxiang()));
		}

		shangjia.setId(new Date().getTime());
		shangjiaService.save(shangjia);
		return R.ok();
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@Transactional
	public R update(@RequestBody ShangjiaEntity shangjia,
					HttpServletRequest request) {
		// ValidatorUtils.validateEntity(shangjia);

		// 新增：处理头像URL
		if (StringUtils.isNotBlank(shangjia.getTouxiang())) {
			shangjia.setTouxiang(ensureFullUrl(shangjia.getTouxiang()));
		}

		shangjiaService.updateById(shangjia);
		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/delete")
	public R delete(@RequestBody Long[] ids) {
		shangjiaService.removeByIds(Arrays.asList(ids));
		return R.ok();
	}

	/**
	 * 提醒接口
	 */
	@GetMapping("/remind/{columnName}/{type}")
	public R remindCount(@PathVariable("columnName") String columnName,
						 HttpServletRequest request,
						 @PathVariable("type") String type,
						 @RequestParam Map<String, Object> map) {
		map.put("columnName", columnName);
		map.put("type", type);

		if("2".equals(type)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			Date remindStartDate = null;
			Date remindEndDate = null;
			if(map.get("remindstart") != null) {
				Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH, remindStart);
				remindStartDate = c.getTime();
				map.put("remindstart", sdf.format(remindStartDate));
			}
			if(map.get("remindend") != null) {
				Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH, remindEnd);
				remindEndDate = c.getTime();
				map.put("remindend", sdf.format(remindEndDate));
			}
		}

		QueryWrapper<ShangjiaEntity> wrapper = new QueryWrapper<>();
		if(map.get("remindstart") != null) {
			wrapper.ge(columnName, map.get("remindstart"));
		}
		if(map.get("remindend") != null) {
			wrapper.le(columnName, map.get("remindend"));
		}

		long  count= shangjiaService.count(wrapper);
		return R.ok().put("count", count);
	}

	/**
	 * 新增：确保URL是完整的OSS URL
	 */
	private String ensureFullUrl(String url) {
		if (StringUtils.isBlank(url)) {
			return url;
		}

		// 如果已经是完整URL，直接返回
		if (url.startsWith("http://") || url.startsWith("https://")) {
			return url;
		}

		// 如果是相对路径，添加OSS基础URL
		if (StringUtils.isNotBlank(ossBaseUrl)) {
			return ossBaseUrl + url;
		}

		// 如果没有配置OSS基础URL，返回原始URL
		return url;
	}
}